package com.bieyang.anjia.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.SubUtils;

/**
 * 报警方式
 * 
 * @author M.y.q
 * 
 */
public class AlarmMethodsActivity extends BaseNomalActivity {
	ListView methodListView;
	SimpleAdapter adapter;
	List<HashMap<String, Object>> list;
	int currentPosition = -1;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.SET_SUB_SET_SUCCESS:
				progressDialog.dismiss();
				Log.d("saveSetting", "success");
				SharedPrefsUtil
						.putValue(
								AlarmMethodsActivity.this,
								Constants.AlARM_METHODS,
								currentPosition == -1 ? getString(R.string.sub_take_video)
										: list.get(currentPosition)
												.get(Constants.SUB_NAME)
												.toString());
				setResult(2005);
				Show.toast(con, R.string.save_device_ok);
				finish();
				break;
			case Constants.SET_SUB_SET_FAILED:
				progressDialog.dismiss();
				Show.toast(con, R.string.save_device_fail);
				finish();
				break;

			default:
				break;
			}
		};
	};

	@Override
	void setContent() {
		setContentView(R.layout.alarm_voice_layout);
	}

	@Override
	void initView() {
		TextView titleName = (TextView) findViewById(R.id.topLineTitle);
		titleName.setText(getString(R.string.sub_alarm_methods));
		TextView tvTitle = (TextView) findViewById(R.id.alarm_desc);
		tvTitle.setText(getString(R.string.sub_methods_desc));
		methodListView = (ListView) findViewById(R.id.alarm_listview);
	}

	@Override
	void initData() {
		list = new ArrayList<HashMap<String, Object>>();
		initList();
		adapter = new SimpleAdapter(this, list,
				R.layout.alarm_listview_item_layout, new String[] { "name",
						"desc", "check" }, new int[] { R.id.alarm_item_name,
						R.id.alarm_item_desc, R.id.alarm_item_check });
		methodListView.setAdapter(adapter);
	}

	private void initList() {

		addMapToList(getString(R.string.sub_take_one),
				getString(R.string.sub_one_desc), 0);
		addMapToList(getString(R.string.sub_take_three),
				getString(R.string.sub_three_desc), 1);
		addMapToList(getString(R.string.sub_take_video),
				getString(R.string.sub_video_desc), 2);
	}

	private void addMapToList(String voiceName, String desc, int position) {
		String currentMethods = SharedPrefsUtil.getStringValue(this,
				Constants.AlARM_METHODS, getString(R.string.sub_take_video));
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put(Constants.SUB_NAME, voiceName);
		map.put(Constants.SUB_DESC, desc);
		if (null != currentMethods && currentMethods.equals(voiceName)) {
			map.put(Constants.SUB_CHECK, true);
			currentPosition = position;
		} else {
			map.put(Constants.SUB_CHECK, false);
		}
		list.add(map);

	}

	@Override
	void setListener() {
		// TODO Auto-generated method stub
		methodListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				isSetted = true;
				CheckBox check = (CheckBox) view
						.findViewById(R.id.alarm_item_check);
				boolean isChecked = check.isChecked();
				HashMap<String, Object> map = list.get(position);
				if (currentPosition != -1) {
					HashMap<String, Object> preMap = list.get(currentPosition);
					preMap.put(Constants.SUB_CHECK, false);
					list.remove(currentPosition);
					list.add(currentPosition, preMap);
				}

				map.put(Constants.SUB_CHECK, !isChecked);
				list.remove(position);
				list.add(position, map);
				if (isChecked) {
					currentPosition = -1;
				} else {
					currentPosition = position;
				}
				adapter.notifyDataSetChanged();
			}

		});
	}

	protected void saveStatus() {
		super.saveStatus();
		if (!isSetted) {
			finish();
			return;
		}
		upLoadDeviceSet(handler);
	}

	/**
	 * 上传采集端机设置 从本地取得设置信息后给device赋值并上传至服务器
	 * */
	public void upLoadDeviceSet(Handler handler) {
		Log.d("subonline", NetManager.subOnLineMap.get(uuid).toString());
		if (App.isLogin) {
			if (!NetManager.subOnLineMap.get(uuid).toString().equals("ONLINE")) {
				Show.toast(con, R.string.sub_off_line);
				return;
			}
		} else {
			Show.toast(con, R.string.please_login);
			return;
		}
		if (null == progressDialog) {
			progressDialog = SubUtils.showProgress(con);
		} else {
			progressDialog.show();
		}
		Device device = new Device();
		device.setDiviceId(id);
		device.setUuid(uuid);
		String dayStart = SharedPrefsUtil.getStringValue(con,
				Constants.DAY_MODE_START_TIME,
				getString(R.string.sub_mode_start_time));
		String dayStop = SharedPrefsUtil.getStringValue(con,
				Constants.DAY_MODE_STOP_TIME,
				getString(R.string.sub_mode_stop_time));
		String mesures = SharedPrefsUtil.getStringValue(con,
				Constants.ALARM_MEASURES, getString(R.string.sub_body_recg));
		String alarm = currentPosition == -1 ? getString(R.string.sub_take_video)
				: list.get(currentPosition).get(Constants.SUB_NAME).toString();
		String voice = SharedPrefsUtil.getStringValue(con,
				Constants.AlARM_PLAY_VOICE,
				getString((R.string.sub_states_null)));
		String nightStart = SharedPrefsUtil.getStringValue(con,
				Constants.NIGHT_MODE_START_TIME,
				getString(R.string.sub_mode_stop_time));
		String nightStop = SharedPrefsUtil.getStringValue(con,
				Constants.NIGHT_MODE_STOP_TIME,
				getString(R.string.sub_mode_start_time));
		boolean flashLight = SharedPrefsUtil.getBooleanValue(con,
				Constants.FLASH_LIGHT, true);
		TreeSet<Integer> chooseSet = subUtils.getWeekDaySet(
				con,
				SharedPrefsUtil.getSetValue(con, Constants.WEEK_DAY,
						subUtils.initWeekSet(con)));

		device.setStartTWhite(dayStart);
		device.setEndTWhite(dayStop);
		device.setDeterrenceVWhite(voice);
		device.setLarmWhite(alarm);
		device.setStartTNight(nightStart);
		device.setEndTNight(nightStop);
		device.setLarmNight(alarm);
		device.setDeterrenceVNight(voice);
		device.setHumanR(mesures.equals(getString(R.string.sub_body_recg)));
		device.setMotionD(!mesures.equals(getString(R.string.sub_body_recg)));
		device.setFlashlight(flashLight);
		device.setWeekWhite(getWeekStr(chooseSet));
		device.setWeekNight(getWeekStr(chooseSet));
		App.netManager.setCollectionTerminal(device, handler);
	}

	/**
	 * 将TreeSet 变为字符串1,2,3,...等上传
	 * */
	private String getWeekStr(TreeSet<Integer> chooseSet) {
		StringBuffer sb = new StringBuffer("");
		Iterator<Integer> it = chooseSet.iterator();
		while (it.hasNext()) {
			int day = it.next();
			sb.append(day);
			sb.append(",");
		}
		String week = sb.toString();
		return week.substring(0, week.length() - 1);
	}
}
